package com.wispx.gateway.core.helper;

import com.wispx.gateway.config.helper.RouteResolver;
import com.wispx.gateway.config.manager.DynamicConfigManager;
import com.wispx.gateway.config.pojo.RouteDefinition;
import com.wispx.gateway.core.context.GatewayContext;
import com.wispx.gateway.core.request.GatewayRequest;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

public class GatewayContextHelper {

    private GatewayContextHelper() {

    }

    /**
     * netty上下文、netty的请求 构建 GatewayContext
     *
     * @param ctx     netty上下文
     * @param request netty的请求
     * @return GatewayContext
     */
    public static GatewayContext buildGatewayContext(ChannelHandlerContext ctx, FullHttpRequest request) {
        RouteDefinition route = RouteResolver.matchRoute(request.uri());
        GatewayRequest gatewayRequest = GatewayRequestHelper
                .buildGatewayRequest(
                        DynamicConfigManager.getInstance().getServiceByServiceName(route.getServiceName()),
                        ctx, request);
        return new GatewayContext(ctx, gatewayRequest, route, HttpUtil.isKeepAlive(request));
    }

    /**
     * 将 HTTP 响应写回客户端
     */
    public static void writeBack2Client(GatewayContext gatewayContext) {
        // 构建HTTP响应
        FullHttpResponse httpResponse = GatewayResponseHelper.buildHttpResponse(gatewayContext);
        ChannelHandlerContext nettyContext = gatewayContext.getNettyContext();
        if (gatewayContext.isKeepAlive()) { // 长连接
            httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            nettyContext.writeAndFlush(httpResponse);
        } else {// 短连接
            httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
            nettyContext.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
        }

    }

}
